<template>
  <div class="echarts">
    <div id="myChart" ref="chartDom" style="width: 400px; height: 220px" />
  </div>
</template>

<script setup lang="ts" name="PieChart">
import * as echarts from "echarts";
import { ref, watch, onMounted } from "vue";
import { getAqiDistribution } from "@/api/aqiMeasuredResult";

defineOptions({
  name: "PieChart"
});

const chartDom = ref(null);
const option = {
  title: {
    text: "空气质量指数级别分布",
    left: "center",
    top: "5%", // 将标题向下移动
    textStyle: {
      color: "white" // 将标题字体颜色设置为白色
    }
  },
  tooltip: {
    trigger: "item"
  },
  legend: {
    orient: "vertical",
    left: 10, // 将图例放在左侧
    top: "middle",
    align: "left",
    verticalAlign: "middle",
    borderRadius: 4,
    itemGap: 20,
    textStyle: {
      color: "white" // 将图例字体颜色设置为白色
    }
  },
  series: [
    {
      name: "AQI",
      type: "pie",
      radius: "50%",
      center: ["65%", "55%"], // 将饼图的位置向右移动
      data: [
        { value: 0, name: "优" },
        { value: 0, name: "良" },
        { value: 0, name: "轻度污染" },
        { value: 0, name: "中度污染" },
        { value: 0, name: "重度" },
        { value: 0, name: "严重" }
      ],
      label: {
        show: true,
        color: "white" // 将字体颜色设置为白色
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    }
  ]
};

const tableData = ref([]);
const getAqiIndexDistribution = async () => {
  try {
    const { data } = await getAqiDistribution();
    tableData.value = data;
    console.log(tableData.value);
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  const myChart = echarts.init(chartDom.value);
  option && myChart.setOption(option);
  getAqiIndexDistribution();
  watch(tableData, newVal => {
    if (newVal && newVal.length > 0) {
      option.series[0].data = newVal.map(item => ({
        value: item.aqiDistribution,
        name: item.aqiLevelDes
      }));
      myChart.setOption(option);
    }
  });

  let currentIndex = -1;
  // 使用setInterval函数每秒更新一次高亮显示的数据
  setInterval(function () {
    var dataLen = option.series[0].data.length;
    // 取消之前高亮的图形
    myChart.dispatchAction({
      type: "downplay",
      seriesIndex: 0,
      dataIndex: currentIndex
    });
    currentIndex = (currentIndex + 1) % dataLen;
    // 高亮当前图形
    myChart.dispatchAction({
      type: "highlight",
      seriesIndex: 0,
      dataIndex: currentIndex
    });
    // 显示 tooltip
    myChart.dispatchAction({
      type: "showTip",
      seriesIndex: 0,
      dataIndex: currentIndex
    });
  }, 1000);
});
</script>

<style></style>
